type MessageType = {
  handle: "occupy" | "release"
  userId: number
  fileId: number
  name: string
}

export const websocket = {
  ws: null as WebSocket | null,
  status: false,
  userId: 0,
  url: "",
  connect(url: string, userId: number) {
    const ws = new WebSocket(url)
    ws.onopen = () => {
      ws.send(JSON.stringify({ userId }))
    }
    ws.onmessage = this.onmessage
    ws.onclose = this.onclose
    ws.onerror = this.onerror
    this.status = true
    this.ws = ws
    this.userId = userId
    this.url = url
  },
  onmessage(e: any) {
    if ((e.data as MessageType | "pong") === "pong") {
      this.status = true
    } else {
      websocket.messageCallback(JSON.parse(e.data))
    }
  },
  messageCallback(e: MessageType) {},
  onerror() {
    websocket.status = false
  },
  onclose() {
    websocket.status = false
  },
  heartbeat() {
    setInterval(() => {
      if (this.status) {
        try {
          ;(this.ws as WebSocket).send("ping")
        } catch {
          this.status = false
          this.connect(this.url, this.userId)
        }
      } else {
        this.connect(this.url, this.userId)
      }
    }, 3000)
  },
}
